<template>
  <div class="auth-page">
    <div class="back-home">
      <el-button type="text" @click="goHome" class="back-btn">
        <el-icon><ArrowLeft /></el-icon> 返回首页
      </el-button>
    </div>
    
    <div class="auth-container">
      <div class="auth-card">
        <div class="auth-header">
          <div class="logo-container">
            <img src="../../assets/logo.png" alt="自驾游探索" class="auth-logo" />
          </div>
          <h1>欢迎回来</h1>
          <p>登录您的账户，继续您的自驾探索之旅</p>
        </div>
        
        <el-form 
          ref="loginFormRef" 
          :model="loginForm" 
          :rules="loginRules" 
          class="auth-form"
        >
          <div v-if="loginError" class="login-error-message">
            <el-alert
              :title="loginError"
              type="error"
              :closable="false"
              show-icon
            />
          </div>
          
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              placeholder="用户名/邮箱"
              :prefix-icon="User"
              size="large"
              class="custom-input"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="密码"
              :prefix-icon="Lock"
              show-password
              size="large"
              class="custom-input"
            />
          </el-form-item>
          
          <div class="form-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-button type="text" class="forgot-password" @click="showForgotPassword">忘记密码?</el-button>
          </div>
          
          <el-button 
            type="primary" 
            class="submit-btn" 
            :loading="userStore.loading"
            @click="handleLogin"
            size="large"
          >
            登录
          </el-button>
        </el-form>
        
        <div class="social-login">
          <div class="social-divider">
            <span>或使用以下方式登录</span>
          </div>
          <div class="social-icons">
            <el-button class="social-icon wechat" circle @click="socialLogin('wechat')">
              <i class="fab fa-weixin"></i>
            </el-button>
            <el-button class="social-icon qq" circle @click="socialLogin('qq')">
              <i class="fab fa-qq"></i>
            </el-button>
            <el-button class="social-icon weibo" circle @click="socialLogin('weibo')">
              <i class="fab fa-weibo"></i>
            </el-button>
          </div>
        </div>
        
        <div class="auth-footer">
          <p>还没有账号? <el-button type="text" @click="goToRegister" class="register-link">立即注册</el-button></p>
        </div>
      </div>
      
      <div class="auth-background">
        <div class="bg-pattern"></div>
        <div class="bg-quote">
          <h2>"旅行是一种心灵的修行，<br>让我们在路上发现更好的自己。"</h2>
          <p>— 自驾游探索</p>
        </div>
      </div>
    </div>
    
    <!-- 添加忘记密码组件 -->
    <ForgotPassword ref="forgotPasswordRef" @success="handlePasswordResetSuccess" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { User, Lock, ArrowLeft } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import ForgotPassword from '@/components/auth/ForgotPassword.vue';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const loginFormRef = ref(null);
const loginError = ref('');

const loginForm = reactive({
  username: '',
  password: ''
});

const rememberMe = ref(localStorage.getItem('rememberMe') === 'true');

const loginRules = {
  username: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 16, message: '密码长度必须在8-16之间', trigger: 'blur' }
  ]
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  
  loginError.value = '';
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await userStore.login(loginForm);
        
        if (response) {
          localStorage.setItem('rememberMe', rememberMe.value);
          
          if (rememberMe.value) {
            localStorage.setItem('rememberedUsername', loginForm.username);
          } else {
            localStorage.removeItem('rememberedUsername');
          }
          
          const redirectPath = route.query.redirect || '/';
          router.push(redirectPath);
        }
      } catch (error) {
        console.error('登录失败:', error);
        if (error.message === '服务器内部错误: User is disabled') {
          error.message = '登录失败，您的账户已被禁用，请联系管理员';
        }
        loginError.value = error.message || '登录失败，请检查用户名和密码';
        
        loginFormRef.value.clearValidate();
        
        const formEl = loginFormRef.value.$el;
        formEl.classList.add('shake');
        setTimeout(() => {
          formEl.classList.remove('shake');
        }, 500);
      }
    } else {
      return false;
    }
  });
};

const goToRegister = () => {
  const username = loginForm.username || '';
  
  loginForm.password = '';
  
  router.push({
    path: '/register',
    query: { username }
  });
};

const showForgotPassword = () => {
  forgotPasswordRef.value.open();
};

const handlePasswordResetSuccess = () => {
  ElMessage.success('密码已重置，请使用新密码登录');
};

const socialLogin = (platform) => {
  ElMessage.info(`${platform}登录功能正在开发中...`);
};

const goHome = () => {
  router.push('/');
};

// 忘记密码组件引用
const forgotPasswordRef = ref(null);

onMounted(() => {
  if (localStorage.getItem('rememberMe') === 'true') {
    const rememberedUsername = localStorage.getItem('rememberedUsername');
    if (rememberedUsername) {
      loginForm.username = rememberedUsername;
    }
  }
});
</script>

<style scoped>
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css');

.auth-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  padding: 20px;
}

.auth-container {
  display: flex;
  width: 100%;
  max-width: 1000px;
  min-height: 600px;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.auth-card {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-container {
  margin-bottom: 20px;
}

.auth-logo {
  height: 60px;
}

.auth-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
  font-weight: 600;
}

.auth-header p {
  color: #606266;
  font-size: 16px;
}

.auth-form {
  margin-bottom: 20px;
}

.custom-input {
  --el-input-height: 50px;
  --el-input-border-radius: 8px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-password {
  color: #409EFF;
  font-size: 14px;
}

.submit-btn {
  width: 100%;
  height: 50px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #409EFF 0%, #007BFF 100%);
  border: none;
}

.social-login {
  margin-top: 10px;
  margin-bottom: 20px;
}

.social-divider {
  position: relative;
  text-align: center;
  margin-bottom: 20px;
}

.social-divider::before,
.social-divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 35%;
  height: 1px;
  background-color: #dcdfe6;
}

.social-divider::before {
  left: 0;
}

.social-divider::after {
  right: 0;
}

.social-divider span {
  display: inline-block;
  padding: 0 10px;
  background-color: #fff;
  position: relative;
  z-index: 1;
  color: #909399;
  font-size: 14px;
}

.social-icons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.social-icon {
  width: 44px;
  height: 44px;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  border: 1px solid #dcdfe6;
}

.social-icon:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.wechat {
  color: #07C160;
}

.qq {
  color: #12B7F5;
}

.weibo {
  color: #E6162D;
}

.auth-footer {
  margin-top: auto;
  text-align: center;
  color: #606266;
}

.register-link {
  color: #409EFF;
  font-weight: 500;
}

.auth-background {
  flex: 1;
  background: linear-gradient(135deg, #3498db 0%, #1abc9c 100%);
  position: relative;
  display: none;
  overflow: hidden;
}

.bg-pattern {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('');
  opacity: 0.2;
}

.bg-quote {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  text-align: center;
  width: 80%;
}

.bg-quote h2 {
  font-size: 24px;
  font-weight: 300;
  line-height: 1.5;
  margin-bottom: 20px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.bg-quote p {
  font-size: 16px;
  opacity: 0.8;
}

@media (min-width: 768px) {
  .auth-background {
    display: block;
  }
}

@media (max-width: 767px) {
  .auth-container {
    flex-direction: column;
  }
  
  .auth-card {
    padding: 30px 20px;
  }
}

.back-home {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
}

.back-btn {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #606266;
  transition: all 0.3s;
}

.back-btn:hover {
  color: #409EFF;
  transform: translateX(-5px);
}

.back-btn .el-icon {
  margin-right: 5px;
}

@media (max-width: 767px) {
  .back-home {
    top: 10px;
    left: 10px;
  }
  
  .back-btn {
    font-size: 14px;
  }
}

.login-error-message {
  margin-bottom: 15px;
}

/* 当有登录错误消息时，隐藏表单字段的验证错误消息 */
.login-error-message + .el-form-item .el-form-item__error {
  display: none;
}

/* 添加震动效果 */
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.shake {
  animation: shake 0.5s;
}
</style> 